package x.ovo.wechat.bot.plugin;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpUtil;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import x.ovo.wechat.bot.core.event.EventListener;
import x.ovo.wechat.bot.core.event.MessageEvent;
import x.ovo.wechat.bot.core.message.TextMessage;
import x.ovo.wechat.bot.core.plugin.Plugin;

import java.io.File;

@Slf4j(topic = "DailyNews")
public class DailyNewsListener extends EventListener<MessageEvent<TextMessage>, TextMessage> {

    private static final String NEWS_URL = "https://api.jun.la/60s.php?format=image";
    private static final String CHIGUA_URL = "https://dayu.qqsuu.cn/mingxingbagua/apis.php";

    public DailyNewsListener(Plugin plugin) {
        super(plugin);
    }

    @Override
    public boolean support(@NonNull MessageEvent<TextMessage> textMessageMessageEvent, TextMessage textMessage) {
        return "今日新闻".equals(textMessage.getContent()) || "今日吃瓜".equals(textMessage.getContent());
    }

    @Override
    public boolean onEvent(@NonNull MessageEvent<TextMessage> textMessageMessageEvent, TextMessage textMessage) {
        if ("今日新闻".equals(textMessage.getContent())) this.getNews(textMessage);
        if ("今日吃瓜".equals(textMessage.getContent())) this.getGua(textMessage);
        return true;
    }

    private void getNews(TextMessage textMessage) {
        // 获取今日日期
        String today = DateUtil.today();
        File file = FileUtil.file(this.plugin.getDataDir(), today + ".png");
        // 判断今日文件是否存在，存在则直接发送，否则删除数据文件夹中的文件再重新下载今日的文件
        if (FileUtil.exist(file)) {
            textMessage.getFrom().sendImage(file);
        } else {
            try {
                FileUtil.del(this.plugin.getDataDir());
                HttpUtil.downloadFile(NEWS_URL, file);
                boolean b = textMessage.getFrom().sendImage(file);
                log.info("发送每日新闻{}", b ? "成功" : "失败");
            } catch (Exception e) {
                log.error("发送每日新闻失败", e);
            }
        }
    }

    private void getGua(TextMessage textMessage) {
        try {
            File file = FileUtil.file(this.plugin.getDataDir(), "chigua.png");
            HttpUtil.downloadFile(CHIGUA_URL, file);
            boolean b = textMessage.getFrom().sendImage(file);
            log.info("发送每日吃瓜{}", b ? "成功" : "失败");
        } catch (Exception e) {
            log.error("发送每日吃瓜失败", e);
        }
    }

    @Override
    public boolean executeNext() {
        return false;
    }
}
